<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 5/27 0027
 * Time: 11:47
 */

namespace app\api\model;


use think\Model;

class Chargeorder extends Model
{
    /**
     * 生成一个订单并返回信息
     */
    public function addorder($userid,$chargeid,$memberno){
//        需要检验memberno是否存在
//        return ["status"=>0,"msg"=>"会员卡号不存在!"];
        $orderno=$this->orderno();
        $gradient=model("gradient")->where("id",$chargeid)->find();
        if(empty($gradient)){
            return ["status"=>0,"data"=>"","msg"=>"充值梯度不存在"];
        }
        $shopinfo=model("manager")->where("y_manager.id",$userid)->join("y_shop","y_shop.id=y_manager.shopid","left")->find();
        if (!$shopinfo) {
            return ["status"=>0,"msg"=>"无门店"];
        } else {
            if(!$shopinfo['ttgid']){
                return ["status"=>0,"msg"=>"淘淘谷配置错误"];
            }
            $res =$this->save([
                "memberno"=>$memberno,
                "orderno"=>$orderno,
                "fee"=>$gradient["money"],
                "managerid"=>$userid,
                "ord_type"=>3,
                "ord_add_time"=>time(),
                "ord_status"=>2
            ]);
            if($res){
                return [
                    "status"=>1,
                    "msg"=>"success",
                    "data"=> [
                        'fee'=>$gradient["money"],
                        'ord_no'=>$orderno,
                        'open_id' => $shopinfo['openid'],
                        'open_key' => $shopinfo['openkey'],
                        'notifyurl'=>"http://xtshop.xwdcook.com/index.php/api/Notify/chargenotify/ttgid/{$shopinfo['ttgid']}",
                        'customname'=>$shopinfo['nickname'],
                        'taostorenum'=>$shopinfo['ttgshopno'],
                        'customid'=>str_pad($userid,6,0,STR_PAD_LEFT)
                    ]
                ];
            }else{
                return ["status"=>0,"msg"=>"订单保存失败"];
            }
        }
    }

    /**
     * 生成一个随机订单号
     * @return string
     */
    private function orderno(){
        $orderSn = (intval(date('Y')) - 2017) . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }

}